package com.badboy.service;

import com.badboy.entity.Users;
import com.badboy.mapper.UsersMapper;
import com.badboy.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

public class UserService {


    /**
            * 用户登录
     * @param email 邮箱
     * @param password 密码
     * @return 登录成功的用户对象，失败返回null
     */
    public Users login(String email, String password) {
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            UsersMapper mapper = sqlSession.getMapper(UsersMapper.class);
            return mapper.findUserByEmailAndPassword(email, password);
        }
    }

    /**
            * 用户注册
     * @param username 用户名
     * @param email 邮箱
     * @param password 密码
     * @return 注册成功的用户对象，失败返回null
     */
    public Users register(String username, String email, String password) {
        // 使用自动提交设置为false，以便手动控制事务
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession(false)) {
            UsersMapper mapper = sqlSession.getMapper(UsersMapper.class);

            // 检查邮箱是否已注册
            if (mapper.findUserByEmail(email) != null) {
                throw new RuntimeException("该邮箱已被注册");
            }

            // 创建新用户
            Users newUser = new Users();
            newUser.setUsername(username);
            newUser.setEmail(email);
            newUser.setPassword(password);
            // 用户注册时间
            newUser.setCreatedAt(new java.util.Date());
            // 设置用户角色，0为普通用户
            newUser.setIsAdmin(0);
            // 是否为板块版主，0为普通用户
            newUser.setIsModerator(0);

            // 插入数据库
            int result = mapper.insert(newUser);
            if (result <= 0) {
                sqlSession.rollback();
                throw new RuntimeException("用户注册失败");
            }

            sqlSession.commit();
            return newUser;
        } catch (Exception e) {
            throw new RuntimeException("注册过程中发生错误: " + e.getMessage());
        }
    }

    /**
            * 检查邮箱是否已注册
     * @param email 邮箱
     * @return 已注册返回true，否则返回false
     */
    public boolean isEmailRegistered(String email) {
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            UsersMapper mapper = sqlSession.getMapper(UsersMapper.class);
            return mapper.findUserByEmail(email) != null;
        }
    }



}